<template>
  <div class="mqtt-manager">
    <div class="header">
      <h2>MQTT通道管理</h2>
      <el-button type="primary" @click="showAddDialog">添加通道</el-button>
    </div>

    <!-- 通道列表 -->
    <el-table :data="topics" v-loading="loading" border style="width: 100%; margin-top: 20px;">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="topic" label="主题" width="180" />
      <el-table-column prop="description" label="描述" width="200" />
      <el-table-column prop="table_name" label="关联表" width="180" />
      <el-table-column prop="active" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.active ? 'success' : 'info'">
            {{ scope.row.active ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" width="180">
        <template #default="scope">
          {{ new Date(scope.row.created_at).toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button-group>
            <el-button
              type="warning"
              size="small"
              @click="showEditDialog(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑通道对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '添加通道' : '编辑通道'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        style="max-width: 460px"
      >
        <el-form-item label="主题" prop="topic">
          <el-input v-model="form.topic" placeholder="请输入主题" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入描述信息" />
        </el-form-item>
        <el-form-item label="关联表" prop="table_name">
          <el-select v-model="form.table_name" placeholder="请选择关联表">
            <el-option
              v-for="table in tables"
              :key="table.name"
              :label="table.name"
              :value="table.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" v-if="dialogType === 'edit'">
          <el-switch v-model="form.active" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 生成随机字符串
const generateRandomString = (length) => {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length))
  }
  return result
}

// 生成主题
const generateTopic = () => {
  const timestamp = Date.now()
  const randomValue = generateRandomString(10)
  return `PCWX/${timestamp}/${randomValue}`
}

// 状态变量
const loading = ref(false)
const topics = ref([])
const tables = ref([])
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)

// 表单数据
const form = ref({
  id: '',
  topic: '',
  description: '',
  table_name: '',
  active: true
})

// 表单验证规则
const rules = {
  topic: [
    { required: true, message: '请输入主题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入描述信息', trigger: 'blur' }
  ],
  table_name: [
    { required: true, message: '请选择关联表', trigger: 'change' }
  ]
}

// 获取通道列表
const fetchTopics = async () => {
  loading.value = true
  try {
    const token = localStorage.getItem('token')
    const response = await fetch('https://PengLink.pcwxcn.top/api/mqtt/topics', {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    })

    // console.log('MQTT 通道响应状态:', response.status)
    const responseText = await response.text()
    // console.log('MQTT 通道响应内容:', responseText)

    if (!response.ok) {
      throw new Error(`获取通道列表失败: ${response.status} ${response.statusText}`)
    }

    const result = JSON.parse(responseText)
    if (result.code === 200) {
      topics.value = Array.isArray(result.data) ? result.data : []
    } else {
      throw new Error(result.message || '获取通道列表失败')
    }
  } catch (error) {
    // console.error('获取通道列表失败:', error)
    ElMessage.error(error.message)
  } finally {
    loading.value = false
  }
}

// 获取表格列表
const fetchTables = async () => {
  try {
    // 这里暂时使用硬编码的表格列表，后续可以替换为实际的 API
    tables.value = [
      { name: 'OilTable1' },
      { name: 'CurrencyOilTable1' }
    ]
  } catch (error) {
    // console.error('获取表格列表失败:', error)
    ElMessage.error(error.message)
  }
}

// 显示添加对话框
const showAddDialog = () => {
  dialogType.value = 'add'
  form.value = {
    topic: generateTopic(), // 自动生成主题
    description: '',
    table_name: '',
    active: true
  }
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (row) => {
  dialogType.value = 'edit'
  form.value = {
    id: row.id,
    topic: row.topic,
    description: row.description,
    table_name: row.table_name,
    active: row.active
  }
  dialogVisible.value = true
}

// 添加或更新通道
const handleSave = async () => {
  if (!form.value) return
  
  try {
    loading.value = true
    const token = localStorage.getItem('token')
    const authHeader = `Bearer ${token}`

    if (dialogType.value === 'add') {
      // 添加通道
      const response = await fetch('https://PengLink.pcwxcn.top/api/mqtt/topics', {
        method: 'POST',
        headers: {
          'Authorization': authHeader,
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify(form.value)
      })

      if (!response.ok) {
        throw new Error(`添加通道失败: ${response.status} ${response.statusText}`)
      }

      const result = await response.json()
      if (result.code === 200) {
        ElMessage.success('添加成功')
        dialogVisible.value = false
        fetchTopics()
      } else {
        throw new Error(result.message || '添加通道失败')
      }
    } else {
      // 更新通道
      const response = await fetch('https://PengLink.pcwxcn.top/api/mqtt/topics', {
        method: 'PUT',
        headers: {
          'Authorization': authHeader,
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify(form.value)
      })

      if (!response.ok) {
        throw new Error(`更新通道失败: ${response.status} ${response.statusText}`)
      }

      const result = await response.json()
      if (result.code === 200) {
        ElMessage.success('更新成功')
        dialogVisible.value = false
        fetchTopics()
      } else {
        throw new Error(result.message || '更新通道失败')
      }
    }
  } catch (error) {
    // console.error('保存通道失败:', error)
    ElMessage.error(error.message)
  } finally {
    loading.value = false
  }
}

// 删除通道
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除通道 "${row.topic}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const token = localStorage.getItem('token')
    const authHeader = `Bearer ${token}`

    const response = await fetch(`https://PengLink.pcwxcn.top/api/mqtt/topics?id=${row.id}`, {
      method: 'DELETE',
      headers: {
        'Authorization': authHeader,
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    })

    if (!response.ok) {
      throw new Error(`删除通道失败: ${response.status} ${response.statusText}`)
    }

    const result = await response.json()
    if (result.code === 200) {
      ElMessage.success('删除成功')
      fetchTopics()
    } else {
      throw new Error(result.message || '删除通道失败')
    }
  } catch (error) {
    if (error.message !== 'cancel') {
      // console.error('删除通道失败:', error)
      ElMessage.error(error.message)
    }
  }
}

onMounted(() => {
  fetchTopics()
  fetchTables()
})
</script>

<style scoped>
.mqtt-manager {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}

:deep(.el-form-item__content) {
  flex-wrap: nowrap;
}
</style>
